<template>
    <div>
        <el-form :rules="rules"
                 v-loading="loading"
                 element-loading-text="正在登录..."
                 element-loading-spinner="el-icon-loading"
                 element-loading-background="rgba(0, 0, 0, 0.8)"
                 ref="loginForm"
                 :model="loginForm"
                 class="loginContainer">
<!--            2D娘容器存放位置-->
            <div id="stage">
                <div id="inner">
                    <div id="cover">
                        <div id="text">
                            <span style="color: cyan;">云</span><span style="color: white;">E</span><span style="color: blue;">办</span>
                        </div>
                        <div id="detail"></div>
                        <div id="handle"></div>
                    </div>
                    <canvas class="mb-4" id="live2d" width="800" height="800"></canvas>
                </div>
                <a id="info" href="javascript:info()" @click="info"><i class="fa fa-lg fa-info"></i></a>
                <a id="refresh" href="javascript:refresh()"><i class="fa fa-lg fa-refresh"></i></a>
            </div>
            <h3 class="loginTitle">系统登录</h3>
            <el-form-item prop="username">
                <el-input type="text" auto-complete="false" v-model="loginForm.username"
                          placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" auto-complete="false" v-model="loginForm.password"
                          placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item prop="code">
                <el-input type="text" auto-complete="false" v-model="loginForm.code" placeholder="点击图片更换验证码"
                          style="width: 250px;margin-right: 5px"></el-input>
                <img :src="captchaUrl" @click="updateCaptcha">
            </el-form-item>
            <el-checkbox v-model="checked" class="loginRemember">记住我</el-checkbox>
            <el-button type="primary" style="width: 100%" @click="submitLogin">登录</el-button>
        </el-form>

        <el-carousel :height="bannerHeight + 'px'" direction="vertical" :autoplay="true" loop="true">
            <el-carousel-item v-for="item in imagesbox" :key="item.id">
                <img  :src="item.idView" alt="加载失败!" width="100%" height="100%">
            </el-carousel-item>
        </el-carousel>
    </div>
</template>

<script>
    export default {
        name: "Login",
        data() {
            return {
                captchaUrl: '/captcha?time=' + new Date(),
                loginForm: {
                    username: 'admin',
                    password: '123',
                    code: ''
                },
                // 图片父容器高度
                bannerHeight: 500,
                // 浏览器宽度
                screenWidth: 0,
                loading: false,
                checked: true,
                imagesbox:[
                    {
                        id:0,idView:require("../../public/images/a.jpeg")
                    },
                    {
                        id:1,idView:require("../../public/images/b.jpg")
                    },
                    {
                        id:2,idView:require("../../public/images/c.jpg")
                    },
                    {
                        id:3,idView:require("../../public/images/d.jpeg")
                    },
                    {
                        id:4,idView:require("../../public/images/e.jpg")
                    },
                    {
                        id:4,idView:require("../../public/images/f.jpg")
                    }
                ],
                rules: {
                    username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
                    password: [{required: true, message: '请输入密码', trigger: 'blur'}],
                    code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
                },
                mounted(){
                        this.screenWidth = window.innerWidth;
                        this.setSize();
                        // 窗口大小发生改变时,调用一次
                        window.onresize = () => {
                            this.screenWidth = window.innerWidth;
                            this.setSize();
                        }
                }
            }
        },
        methods: {
            setSize() {
                // 通过浏览器宽度(图片宽度)计算高度
                this.bannerHeight = 600 / 1920 * this.screenWidth;
            },
            updateCaptcha() {
                this.captchaUrl = '/captcha?time=' + new Date();
            },
            submitLogin() {
                this.$refs.loginForm.validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        this.postRequest('/login', this.loginForm).then(resp => {
                            this.loading = false;
                            if (resp) {
                                //存储用户token
                                const tokenStr = resp.obj.tokenHead + resp.obj.token;
                                window.sessionStorage.setItem('tokenStr', tokenStr);
                                //页面跳转
                                let path = this.$route.query.redirect;
                                this.$router.replace((path == '/' || path == undefined) ? '/home' : path);
                            }
                        })
                    } else {
                        this.$message.error('请输入所有字段！');
                        return false;
                    }
                });
            },
            info(){
                fetch("https://v1.hitokoto.cn")
                    .then(response => response.json())
                    .then(result => {
                        this.$notify.info({
                            title: '消息',
                            message: "「" + result.hitokoto + "」——" + result.from
                        })
                    });
            }
        }
    }

    //2D娘
    window.addEventListener("load", () => {
        "use strict";
        if (!CSS.supports("clip-path", "circle(120px at center)") && !CSS.supports("-webkit-clip-path", "circle(120px at center)")) {
            document.getElementById("stage").innerHTML = '<img src="../assets/logo.png">';
            return;
        }
        var apiPath = "https://live2d.fghrsh.net/api", state = 0,
            modelId = localStorage.getItem("modelId"),
            modelTexturesId = localStorage.getItem("modelTexturesId");
        if (modelId === null) {
            modelId = 1;
            modelTexturesId = 53;
        }
        loadModel(modelId, modelTexturesId);

        function loadModel(modelId, modelTexturesId) {
            localStorage.setItem("modelId", modelId);
            if (modelTexturesId === undefined) modelTexturesId = 0;
            localStorage.setItem("modelTexturesId", modelTexturesId);
            loadlive2d("live2d", `${apiPath}/get/?id=${modelId}-${modelTexturesId}`, null);
            console.log("live2d", `模型 ${modelId}-${modelTexturesId} 加载完成`);
            setTimeout(() => {
                coverPosition("80%");
                state = 2;
            }, 2000);
        }

        function loadRandModel() {
            var modelId = localStorage.getItem("modelId"),
                modelTexturesId = localStorage.getItem("modelTexturesId");
            fetch(`${apiPath}/rand_textures/?id=${modelId}-${modelTexturesId}`)
                .then(response => response.json())
                .then(result => {
                    loadModel(modelId, result.textures.id);
                    setTimeout(() => {
                        state = 2;
                        coverPosition("80%");
                        document.getElementById("refresh").setAttribute("href", "javascript:refresh()");
                    }, 1000);
                });
        }

        function loadOtherModel() {
            var modelId = localStorage.getItem("modelId");
            fetch(`${apiPath}/switch/?id=${modelId}`)
                .then(response => response.json())
                .then(result => {
                    loadModel(result.model.id);
                });
        }

        function coverPosition(pos) {
            document.getElementById("cover").style.bottom = pos;
        }

        window.refresh = function() {
            state = 0;
            coverPosition("10%");
            document.getElementById("refresh").setAttribute("href", "javascript:void(0)");
            setTimeout(loadRandModel, 1000);
        }

        document.getElementById("handle").addEventListener("click", () => {
            if (state === 1) {
                state = 2;
                coverPosition("80%");
            }
            else if (state === 2) {
                state = 1;
                coverPosition("20%");
            }
        });

        document.querySelector("input[type=password]").addEventListener("focus", () => {
            if (state === 2) {
                state = 1;
                coverPosition("20%");
            }
        });
        document.querySelector("input[type=password]").addEventListener("blur", () => {
            if (state === 1) {
                state = 2;
                coverPosition("80%");
            }
        });
    });
</script>

<style>
    .loginContainer {
        border-radius: 50px;
        background-clip: padding-box;
        width: 350px;
        padding: 15px 35px 15px 35px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
        position: absolute;
        top: 40px;
        right: 120px;
    }

    .loginTitle {
        margin: 0px auto 40px auto;
        text-align: center;
    }

    .loginRemember {
        text-align: left;
        margin: 0px 0px 15px 0px;
    }

    .el-form-item__content {
        display: flex;
        align-items: center;
    }

    html, body {
        height: 100%;
        background: aqua;
    }
    /*左右按钮样式*/
    #stage {
        position: relative;
    }
    /*换装按钮*/
    #stage a {
        position: absolute;
        width: 2em;
        height: 2em;
        border-radius: 50%;
    }
    /*内嵌原框*/
    #inner {
        position: relative;
        background-color: #999;
        clip-path: circle(120px at center);
        -webkit-clip-path: circle(120px at center);
    }
    /*覆盖面板*/
    #cover {
        position: absolute;
        background-color: #CB3837;
        width: 100%;
        height: 100%;
        bottom: 10%;
        transition: all 1s;
        box-shadow: 0 0 0 5px rgba(0, 0, 0, .1);
    }
    /*覆盖面板上的文字*/
    #text {
        position: absolute;
        bottom: 30%;
        font-size: 2em;
        left: 50%;
        transform: translateX(-50%);
        opacity: 0.4;
        font-weight: bold;
    }
    /*交互按钮*/
    #info {
        left: 40px;
        bottom: 20px;
    }
    /*换装按钮*/
    #refresh {
        right: 40px;
        bottom: 20px;
    }
    #live2d {
        cursor: grab;
        height: 300px;
        width: 300px;
        padding-right: 10px;
    }

    .el-carousel{
        width: 66%;
        height: 100%;
        left: 10px;
        top: 100px;
    }

    .el-carousel__item:nth-child(2n) {
        background-color: #99a9bf;
        height: 100%;
    }

    .el-carousel__item:nth-child(2n+1) {
        background-color: #d3dce6;
        height: 100%;
    }
</style>